//
//  CityViewController.m
//  BigToBig
//
//  Created by 毛丽媛 on 16/8/31.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "CityViewController.h"
#import "NH_OrderByPinYinFirstLetter.h"

@interface CityViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating>

@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,retain)NSMutableArray *cityArr;
@property(nonatomic,retain)NSMutableArray *dataArr;
@property(nonatomic,retain)UISearchController *searchController;
@property(nonatomic,retain)NSMutableArray *searchArr;
@property(nonatomic,retain)NSMutableArray *newsArr;
@property(nonatomic,retain)NSMutableArray *cityNameArr;
@property(nonatomic,retain)NSMutableArray *cityIDArr;
@property(nonatomic,retain)NSMutableArray *arr;

@end

@implementation CityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLab.text = self.titleName;
    titleLab.textColor = [UIColor whiteColor];
    [self setBackBar];
    titleLab.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLab;
    
    self.navigationController.navigationBar.translucent = NO;
    
    //创建tableView
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight - 49) style:(UITableViewStyleGrouped)];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"city"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    
    //搜索框
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44);
    //搜索到结果后取消阴影效果
    self.searchController.dimsBackgroundDuringPresentation = false;
    //隐藏tabbar
    self.searchController.hidesBottomBarWhenPushed = NO;
    //隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    //设置代理人
    self.searchController.searchResultsUpdater  = self;
    //设置为tableView的头视图
    self.tableView.tableHeaderView = self.searchController.searchBar;

    [self createData];

}


#pragma mark 过滤数据
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",searchString];
    if (self.searchArr != nil) {
        [self.searchArr removeAllObjects];
    }
    self.searchArr = [NSMutableArray arrayWithArray:[self.cityNameArr filteredArrayUsingPredicate:predicate]];
    
    [self.tableView reloadData];
}

#pragma mark 获取数据
- (void)createData{

    
    [HttpTool postWithURL:@"http://api.meilijia.com/app/advanced_pro_zone_list" params:nil success:^(id json) {
                self.cityArr = [NSMutableArray array];
                self.cityNameArr = [NSMutableArray array];
                self.cityIDArr = [NSMutableArray array];
                for (NSDictionary *temp in json[@"data"][@"advanced_pro_zone_list"][@"show_city"]) {
                    [self.cityArr addObjectsFromArray:temp[@"city_list"]];
                    for (NSDictionary *dic in temp[@"city_list"]) {
                        [self.cityNameArr addObject:dic[@"name"]];
                        NSDictionary *cityDic = @{dic[@"name"]:dic[@"id"]};
                        [self.cityIDArr addObject:cityDic];
        
                    }
                }
                self.dataArr = [NH_OrderByPinYinFirstLetter baseOrderPinYinOnArr:self.cityArr ByKey:@"name"];
                [self.tableView reloadData];
        
        
    } failure:^(NSError *error) {
        
    }];
    
}
#pragma mark 返回cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return self.searchArr.count;
    }
    return [self.dataArr[section][@"datas"]count];
}
#pragma mark 设置section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchController.active) {
        return 1;
    }
    return self.dataArr.count;
}
#pragma mark tableView必须实现的方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"city" forIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor grayColor];
    
    self.newsArr = self.dataArr[indexPath.section][@"datas"];
    if (self.searchController.active) {
        [cell.textLabel setText:self.searchArr[indexPath.row]];
        
        // 搜索时  关键字高亮
        NSMutableAttributedString *att=[[NSMutableAttributedString alloc]initWithString:[self.searchArr objectAtIndex:indexPath.row]];
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:[[self.searchArr objectAtIndex:indexPath.row]rangeOfString:[self.searchController.searchBar text]]];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[[self.searchArr objectAtIndex:indexPath.row]rangeOfString:[self.searchController.searchBar text]]];
        cell.textLabel.attributedText=att;
    }else{
        [cell.textLabel setText:self.newsArr[indexPath.row][@"name"]];
    }
    return cell;
}
#pragma mark 设置分区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.searchController.active) {
        return nil;
    }
    return self.dataArr[section][@"title"];
}
#pragma mark 设置分区快捷条
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *titleArr = [NSMutableArray array];
    for (NSDictionary *dic in self.dataArr) {
        [titleArr addObject:dic[@"title"]];
    }
    return titleArr;
}
#pragma mark 设置分区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
#pragma mark tableView 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    if (self.searchController.active) {
        NSString *name = self.searchArr[indexPath.row];
        for (NSDictionary *temp in self.cityIDArr) {
            if (temp[name] != NULL) {
                NSString *cityID = temp[name];
                [self.delegate bringStr:cityID];
                self.block(self.searchArr[indexPath.row]);
                break;
            }
        }
    }else{
        self.newsArr = self.dataArr[indexPath.section][@"datas"];
        [self.delegate bringStr:self.newsArr[indexPath.row][@"id"]];
        //调用block
        self.block(self.newsArr[indexPath.row][@"name"]);
    }

}
#pragma mark 返回button点击事件
- (void)backAction:(UIButton *)button{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}




- (void)setBackBar{
    
    BackButton *backBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 20, 44);
    [backBtn addTarget:self action:@selector(backController) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
    BackButton *saveBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(kScreenWidth - 44,0 , 44, 44);
    [saveBtn addTarget:self action:@selector(SaveMessage) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
}

- (void)SaveMessage{
    
}

- (void)backController{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
